package com.ity.teamanagement.service.Impl;

import com.ity.teamanagement.code.CommonCode;
import com.ity.teamanagement.code.ImgCode;
import com.ity.teamanagement.entity.TeaQrCode;
import com.ity.teamanagement.entity.outputResult.QrCode;
import com.ity.teamanagement.entity.outputResult.QrCodeList;
import com.ity.teamanagement.entity.outputResult.TeaQrCodeTemp;
import com.ity.teamanagement.exception.ExceptionUtils;
import com.ity.teamanagement.mapper.QrCodeMapper;
import com.ity.teamanagement.service.QrCodeService;
import com.ity.teamanagement.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author coderFu
 * @create 2021/6/4
 */
@Service
public class QrCodeServiceImpl implements QrCodeService {

    @Autowired
    private TeaQrCodeUtils teaQrCodeUtils;

    @Resource
    private QrCodeMapper qrCodeMapper;

    @Resource
    private HttpServletResponse response;



    @Override
    public List<QrCode> produceOneQrCodeById(List<Long> qrIds) {
        System.out.println(qrIds);
        if (qrIds.size() == 0){
            ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
        }
        List<QrCode> qrCodes = new ArrayList<>();
        for (Long qrId : qrIds) {
            QrCode qrCode = new QrCode();
            TeaQrCode teaQrCode = new TeaQrCode();
            Integer flag = qrCodeMapper.findQrIsExist(qrId);
            if (flag>0){
                continue;
            }
            TeaQrCodeTemp teaQrCodeTemp = teaQrCodeUtils.createTeaQrCode(qrId);
            teaQrCode.setCreateTime(new Date());
            teaQrCode.setTeaMessageId(teaQrCodeTemp.getTeaMessageId());
            teaQrCode.setContent(teaQrCodeTemp.getContent());
            teaQrCode.setQrImgId(teaQrCodeTemp.getQrImgId());
            qrCode.setTeaMessageId(teaQrCodeTemp.getTeaMessageId());
            qrCode.setPath(teaQrCodeTemp.getPath());
            Integer count = qrCodeMapper.saveQrCode(teaQrCode);
            qrCodes.add(qrCode);
            if (count<1){
                ExceptionUtils.error(com.ity.teamanagement.code.TeaQrCode.QR_CODE_STORE_FAIL);
            }
        }
        return qrCodes;
    }


    @Override
    public PageableDetails findAllTeaQrCode(Pageable pageable) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        int total = qrCodeMapper.findAllTeaQrCodeCount();
        if (total == 0){
            return new PageableDetails<>(pageNumber,pageSize,total,returnPages(total,pageSize),new ArrayList<>());
        }
        List<QrCodeList> qrCodeLists = qrCodeMapper.findAllTeaQrCode(pageNumber*pageSize,pageSize);
        return new PageableDetails(pageNumber,pageSize,total,returnPages(total,pageSize),qrCodeLists);
    }

    @Override
    public void deleteTeaQrCodeByIds(List<Long> ids) {
        if (ids.size() == 0){
            ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
        }
        List<String> paths = qrCodeMapper.findPathTeaQrCodeByIds(ids);
        for (String path : paths) {
            boolean flag = FileUtils.deleteFile(path);
//            if (!flag){
////                ExceptionUtils.error(ImgCode.IMG_DELETE_ERROR);
//            }
        }
        Integer count = qrCodeMapper.deleteTeaQrCodeByIds(ids);
        if (count<1){
            ExceptionUtils.error(ImgCode.IMG_DELETE_ERROR);
        }
    }

    @Override
    public void downloadTeaQrCodeByIds(List<Long> ids) {
        if (ids.size()== 0){
            ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
        }
        List<QrCodeList> qrCodeLists = qrCodeMapper.findTeaQrCodeByIds(ids);
        List<File> fileList = new ArrayList<>();
        String zipFileName = "茶种二维码"+".zip";
        try {
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(zipFileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
        }
        BufferedOutputStream bos = null;
        for (QrCodeList qrCodeList : qrCodeLists) {
            try {
                String imgPath = FileUtils.getAllImgPath(qrCodeList.getPath());
                File desFile = FileUtils.changeFileName(imgPath, qrCodeList);
                fileList.add(desFile);
                 bos = new BufferedOutputStream(response.getOutputStream());
            } catch (IOException e) {
                ExceptionUtils.error(ImgCode.IMG_NOT_EXIST);
            }
        }
        ZipUtils.toZip(fileList,bos);
        try {
            if (bos !=null) {
                bos.flush();
                bos.close();
            }
            File file = new File(FileUtils.getTempQrCodePath());
            //删除临时文件夹中的文件
            for (File file1 : fileList) {
                file1.delete();
            }
            //删除临时文件夹
            file.delete();
        } catch (IOException e) {
           ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
        }
    }

    @Override
    public void downloadAllTeaQrCodeByIds() {
        List<QrCodeList> allTeaQrCode = qrCodeMapper.backFindAllTeaQrCode();
        List<File> fileList = new ArrayList<>();
        String zipFileName = "茶种二维码"+".zip";
        try {
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(zipFileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
        }
        BufferedOutputStream bos = null;
        for (QrCodeList qrCodeList : allTeaQrCode) {
            try {
                String imgPath = FileUtils.getAllImgPath(qrCodeList.getPath());
                File desFile = FileUtils.changeFileName(imgPath, qrCodeList);
                fileList.add(desFile);
                bos = new BufferedOutputStream(response.getOutputStream());
            } catch (IOException e) {
                ExceptionUtils.error(ImgCode.IMG_NOT_EXIST);
            }
        }
        ZipUtils.toZip(fileList,bos);
        try {
            if (bos !=null) {
                bos.flush();
                bos.close();
            }
            File file = new File(FileUtils.getTempQrCodePath());
            //删除临时文件夹中的文件
            for (File file1 : fileList) {
                file1.delete();
            }
            //删除临时文件夹
            file.delete();
        } catch (IOException e) {
            ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
        }
    }


    public <T> PageableDetails returnPageable(int pageNumber, Integer pageSize, Integer count, List<T> list) {
        return new PageableDetails<>(pageNumber, pageSize, count, list);
    }


    /**
     * 返回总页数
     *
     * @param total
     * @param pageSize
     * @return
     */
    public int returnPages(int total, int pageSize) {
        return PageUtils.returnPages(total, pageSize);
    }

}
